package dao

import (
	"errors"
	"lib/structs/tables"
	"vap/global"
)

var SettingsRepository = new(settingsRepository)

type settingsRepository struct{}

// FindGlobalGuaPropertiesMap 查询全局gua配置
func (r settingsRepository) FindGlobalGuaPropertiesMap() (m map[string]string) {
	m = make(map[string]string)
	var li []tables.GuaProperty
	err := global.DB.Model(&tables.GuaProperty{}).
		Where(&tables.GuaProperty{Scope: tables.ScopeForGlobal}).Find(&li).Error
	if err != nil {
		return
	}
	for _, item := range li {
		m[item.Key] = item.Value
	}
	return
}

// SaveWatermark 更新水印信息
func (r settingsRepository) SaveWatermark(val string) (err error) {
	var d tables.VapSettings
	err = global.DB.Model(&tables.VapSettings{}).Where("key = ?", tables.SettingForWatermark).Find(&d).Error
	if err != nil {
		return
	}
	d.Value = val
	d.Key = tables.SettingForWatermark
	err = global.DB.Save(&d).Error
	return
}

func (r settingsRepository) FindWatermark() (m tables.VapSettings, err error) {
	err = global.DB.Model(&tables.VapSettings{}).Where("key = ?", tables.SettingForWatermark).Find(&m).Error
	return
}

func (r settingsRepository) FindGuaProperties() (li []tables.GuaProperty, err error) {
	err = global.DB.Model(&tables.GuaProperty{}).Find(&li).Error
	return
}

// UpdateGuaProperty 更新gua参数
func (r settingsRepository) UpdateGuaProperty(in tables.GuaProperty) (err error) {
	var m tables.GuaProperty
	err = global.DB.Where("id = ?", in.Id).First(&m).Error
	if err != nil {
		return
	}
	if m.Key != in.Key {
		err = errors.New("需要更新的 k、v 、id 不匹配")
		return
	}
	m.Value = in.Value
	m.Scope = in.Scope
	err = global.DB.Save(&m).Error
	return
}
